package com.example.administrator.yanfoxconn.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.ComAbRouteListAdapter;
import com.example.administrator.yanfoxconn.adapter.DNLookListAdapter;
import com.example.administrator.yanfoxconn.adapter.KLCheckListAdapter;
import com.example.administrator.yanfoxconn.bean.DNCheckMessage;
import com.example.administrator.yanfoxconn.bean.FileName;
import com.example.administrator.yanfoxconn.bean.KLMessage;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Description 安保部 公文查詢
 * @Author song
 * @Date 11/1/21 10:36 AM
 */
public class KLCheckActivity extends BaseActivity implements View.OnClickListener , AdapterView.OnItemClickListener{
    private final int MESSAGE_SET_TYPE = 7;//下拉賦值
    private final int MESSAGE_SET_LIST = 8;//列表賦值

    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題

    @BindView(R.id.sp_type)
    Spinner spType;//類別
    @BindView(R.id.et_name)
    EditText etName;//檔案名稱
    @BindView(R.id.et_area)
    EditText etArea;//試用範圍
    @BindView(R.id.et_dep)
    EditText etDep;//申請單位
    @BindView(R.id.et_car_name)
    EditText etCarName;//姓名
    @BindView(R.id.et_car_num)
    EditText etCarNum;//車牌號
    @BindView(R.id.et_people)
    EditText etPeople;//承辦人
    @BindView(R.id.btn_check)
    Button btnCheck;
    @BindView(R.id.lv_list)
    MyListView lvList;

    private KLCheckListAdapter adapter;
    private List<KLMessage> messages,messageList;
    private String typeC;//選擇的類型

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kl_lv);
        ButterKnife.bind(this);
        tvTitle.setText("公文查詢");
        btnBack.setText("返回");
        btnCheck.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        lvList.setOnItemClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_check:
                check();
                break;
        }
    }

    public void getType() {
        showDialog();
        final String   url = Constants.HTTP_KL_GET_TYPE ;

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);
                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                String response = result;
                dismissDialog();
                if (result != null) {
                    Log.e("---------", "==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("code").getAsString();
                    if (errCode.equals("1")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        messages = new ArrayList<KLMessage>();
                        for (JsonElement type : array) {
                            KLMessage humi = gson.fromJson(type, KLMessage.class);
                            messages.add(humi);
                        }

                        Message message = new Message();
                        message.what = MESSAGE_SET_TYPE;
                        message.obj = messages;
                        mHandler.sendMessage(message);

                    } else if (errCode.equals("0")) {
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = "獲取類別失敗";
                        mHandler.sendMessage(message);
                        messages.clear();
                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    message.obj = "請求不成功";
                }
            }
        }.start();
    }
//    提交前檢查
    private void check() {

        final String url = Constants.HTTP_KL_GET_DETAIL; //此處寫上自己的URL

        JsonObject object = new JsonObject();
        object.addProperty("type",typeC);
        object.addProperty("documentName", etName.getText().toString());
        object.addProperty("scope", etArea.getText().toString());
        object.addProperty("depart",etDep.getText().toString());
        object.addProperty("excuteman", etPeople.getText().toString());
        object.addProperty("carname", etCarName.getText().toString());
        object.addProperty("carnum", etCarNum.getText().toString());
            Log.e("-----object------",  object.toString());

            //開啟一個新執行緒，向伺服器上傳資料
            new Thread() {
                public void run() {
                    //把网络访问的代码放在这里
                    try {
                        showDialog();
                        Log.e("---------", "==fff===" + url);
                        String result = HttpConnectionUtil.doPostJsonObject(url, object);

                        if (result != null) {
                            dismissDialog();
                            Log.e("---------", "result==fff===" + result);
                            Gson gson = new Gson();
                            JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                            String errCode = jsonObject.get("code").getAsString();
                            if (errCode.equals("1")) {

                                Log.e("---------", "errCode==1" + result);
                                JsonArray array = jsonObject.get("data").getAsJsonArray();
                                messageList = new ArrayList<KLMessage>();
                                for (JsonElement type : array) {
                                    KLMessage humi = gson.fromJson(type, KLMessage.class);
                                    messageList.add(humi);
                                }

                                Message message = new Message();
                                message.what = MESSAGE_SET_LIST;
                                message.obj = jsonObject.get("msg").getAsString();
                                mHandler.sendMessage(message);

                            } else{
                                Message message = new Message();
                                message.what = Constants.MESSAGE_TOAST;
                                message.obj = jsonObject.get("msg").getAsString();
                                mHandler.sendMessage(message);
                            }
                        }else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_NETMISTAKE;
                            mHandler.sendMessage(message);
                            finish();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        FileUtil.deletePhotos(KLCheckActivity.this);
                    }
                }
            }.start();
        }




    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case Constants.MESSAGE_TOAST://Toast彈出
//                    ToastUtils.showShort(DNLookListActivity.this, msg.obj.toString());
//                    dnLookListAdapter = new DNLookListAdapter(DNLookListActivity.this, dnCheckMessageList, flag);
//                    lvLook.setAdapter(dnLookListAdapter);
                    break;
                case MESSAGE_SET_TYPE:
                    List<String> ty3 = new ArrayList<String>();
                    ty3.add("全選");
                    for (int i = 0; i < messages.size(); i++) {
                        ty3.add(messages.get(i).getType());
                    }
                    spType.setAdapter(new ArrayAdapter<String>(KLCheckActivity.this, android.R.layout.simple_list_item_1, ty3));
                    spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            if (position==0){
                                typeC="";
                            }else {
                                typeC = ty3.get(position);
                            }
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
                    break;
                case MESSAGE_SET_LIST://列表賦值
                    adapter = new KLCheckListAdapter(KLCheckActivity.this, messageList);
                    Log.e("----------","MESSAGE_SET_LIST");
                    lvList.setAdapter(adapter);
                    setListViewHeightBasedOnChildren(lvList);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onStart() {
        super.onStart();
        getType();
    }

    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        KLCheckListAdapter listAdapter = (KLCheckListAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(KLCheckActivity.this,KLLookPDFActivity.class);
        intent.putExtra("pdf", messageList.get(position).getGenerateName());
        startActivity(intent);
    }
}
